<template>
  <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
    <el-form-item label="上级区域">
      <div class="text-gray-500 text-sm">
        <span v-if="parentRegion"
          >{{ parentRegion.name }} (ID: {{ parentRegion.id }})</span
        >
        <span v-else>无（顶级区域）</span>
      </div>
    </el-form-item>
    <el-form-item label="区域名称" prop="name">
      <el-input
        v-model.trim="form.name"
        placeholder="请输入区域名称"
        clearable
      />
    </el-form-item>
    <el-form-item label="区域编码" prop="code">
      <el-input
        v-model.trim="form.code"
        placeholder="可选，支持字母数字"
        clearable
      />
    </el-form-item>
    <el-form-item label="排序值" prop="sort">
      <el-input-number v-model="form.sort" :min="0" :max="9999" />
    </el-form-item>
    <el-form-item label="状态" prop="status">
      <el-switch
        v-model="form.status"
        inline-prompt
        :active-value="1"
        :inactive-value="0"
        active-text="启用"
        inactive-text="停用"
      />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { createRegion, updateRegion } from "@/api/system/region/region";

interface RegionBasic {
  id: number;
  name: string;
  parent_id?: number;
  sort?: number;
  status?: number;
  code?: string;
}

const props = defineProps<{
  mode: "create" | "edit";
  region?: RegionBasic | null;
  parentRegion?: RegionBasic | null;
}>();

const emit = defineEmits<{ (e: "success"): void }>();

const formRef = ref();

const form = reactive({
  name: props.region?.name ?? "",
  code: props.region?.code ?? "",
  sort: props.region?.sort ?? 0,
  status: props.region?.status ?? 1
});

const parentRegion = computed(() => props.parentRegion ?? null);

const rules = {
  name: [{ required: true, message: "请输入区域名称", trigger: "blur" }],
  code: [
    {
      validator: (_: any, value: string, callback: Function) => {
        if (!value) return callback();
        if (!/^[A-Za-z0-9_-]{0,60}$/.test(value)) {
          callback(new Error("编码仅支持字母、数字、下划线、短横线"));
          return;
        }
        callback();
      },
      trigger: "blur"
    }
  ]
};

const submitForm = async () => {
  const formEl = formRef.value as any;
  if (!formEl) return false;
  const valid = await formEl.validate().catch(() => false);
  if (!valid) return false;

  const payload: Record<string, any> = {
    name: form.name,
    code: form.code,
    sort: form.sort,
    status: form.status
  };

  if (props.mode === "create") {
    payload.parent_id = props.parentRegion?.id ?? 0;
    try {
      await createRegion(payload);
      ElMessage.success("区域已创建");
      emit("success");
      return true;
    } catch (error: any) {
      ElMessage.error(error?.message ?? "创建失败");
      return false;
    }
  }

  if (!props.region) {
    ElMessage.error("缺少区域信息");
    return false;
  }

  try {
    await updateRegion(props.region.id, payload);
    ElMessage.success("区域已更新");
    emit("success");
    return true;
  } catch (error: any) {
    ElMessage.error(error?.message ?? "更新失败");
    return false;
  }
};

defineExpose({
  submitForm
});
</script>
